package com.by.cloud.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.by.cloud.common.BaseContext;
import com.by.cloud.exception.BusinessException;
import com.by.cloud.exception.ErrorCode;
import com.by.cloud.exception.ThrowUtils;
import com.by.cloud.mapper.TagMapper;
import com.by.cloud.model.entity.PictureCategoryTag;
import com.by.cloud.model.entity.Tag;
import com.by.cloud.model.vo.tag.TagVo;
import com.by.cloud.service.PictureCategoryTagService;
import com.by.cloud.service.TagService;
import com.by.cloud.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lzh
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Resource
    private UserService userService;

    @Resource
    private PictureCategoryTagService pictureCategoryTagService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addBatchTags(List<String> tagNameList) {
        // 判断标签是否存在
        List<Tag> tagList = this.list();

        // 如果数据库中有标签，判断标签是否存在
        if (CollUtil.isNotEmpty(tagList)) {
            // 获取两个集合的交集
            Set<String> dbTagNameSet = tagList.stream()
                    .map(Tag::getTagName)
                    .collect(Collectors.toSet());
            Set<String> tagNameSet = new HashSet<>(tagNameList);
            tagNameSet.retainAll(dbTagNameSet);

            // 如果标签存在，则不添加
            if (CollUtil.isNotEmpty(tagNameSet)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签已存在，请重新输入");
            }
        }

        // 获取登录用户ID
        Long userId = BaseContext.getCurrentId();

        // 批量添加标签
        tagList = tagNameList.stream().map(tagName -> {
            Tag tag = new Tag();
            tag.setTagName(tagName);
            tag.setUserId(userId);
            tag.setUseCount(0);
            return tag;
        }).toList();
        return this.saveBatch(tagList);
    }

    @Override
    public List<TagVo> listTags() {
        List<Tag> tagList = this.list();
        // 如果为空，直接返回
        if (CollUtil.isEmpty(tagList)) {
            return Collections.emptyList();
        }
        // 转换为TagVo
        return tagList.stream()
                .map(tag -> BeanUtil.copyProperties(tag, TagVo.class))
                .toList();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeBatchTags(List<Long> ids) {
        // 判断标签是否在使用中
        List<PictureCategoryTag> pictureCategoryTagList = pictureCategoryTagService.lambdaQuery()
                .in(PictureCategoryTag::getTagId, ids)
                .list();
        // 如果在使用中，则不能删除
        if (CollUtil.isNotEmpty(pictureCategoryTagList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签在使用中，不能删除");
        }
        return this.removeBatchByIds(ids);
    }

    @Override
    public List<TagVo> getTagsByPictureId(Long id) {
        ThrowUtils.throwIf(id == null, ErrorCode.PARAMS_ERROR);
        // 获取图片对应的标签，分类关系
        List<PictureCategoryTag> pictureCategoryTagList = pictureCategoryTagService.lambdaQuery()
                .eq(PictureCategoryTag::getPictureId, id)
                .list();
        if (CollUtil.isEmpty(pictureCategoryTagList)) {
            return Collections.emptyList();
        }
        //获取标签集合，然后进行封装
        Set<Long> tagIds = pictureCategoryTagList.stream()
                .map(PictureCategoryTag::getTagId)
                .collect(Collectors.toSet());
        List<Tag> tags = this.listByIds(tagIds);
        return BeanUtil.copyToList(tags, TagVo.class);
    }
}
